package com.tz.online.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;


public class HibernateTemplate {
	
	/**
	 * 模板方法
	 * @param callback
	 * @return
	 */
	public Object execute(HibernateCallback callback) {
		Session ses = null;
		Transaction tx = null;
		Object obj = null;
		try {
			ses = HibernateUtil.getSession();
			tx = ses.beginTransaction();
			//执行回调方法
			obj = callback.doInHibernate(ses);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			//采用线程绑定的session, 无需手动关闭
			//...
		}
		return obj;
	}
}
